import { downFile } from "./downFile";

/**
 * @description: 拉流下载方法
 * @param path 下载url
 * @param defaultName 匹配请求如果没有使用名称
 * @param token 鉴权 Authorization
 * @param params 参数 object
 */
export const downStream = (path: string, defaultName?: string, token?: string, params?: Record<string, any>) => {
  // 处理查询参数
  const queryParams = new URLSearchParams(params).toString();
  const urlWithParams = queryParams ? `${path}?${queryParams}` : path;

  const xhr = new XMLHttpRequest();
  xhr.open("GET", urlWithParams);
  xhr.responseType = "blob";

  if (token) xhr.setRequestHeader("Authorization", token);
  xhr.onload = function () {
    if (xhr.status === 200 || xhr.status === 304) {
      let filename;
      if (defaultName) {
        filename = defaultName;
      } else {
        // 从 Content-Disposition 中提取文件名
        const disposition = xhr.getResponseHeader("Content-Disposition");
        if (disposition && disposition.indexOf("attachment") !== -1) {
          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
          const matches = filenameRegex.exec(disposition);
          if (matches != null && matches[1]) {
            filename = matches[1].replace(/['"]/g, "");
          }
        }
      }
      // 下载文件
      downFile(this.response, filename);
    } else {
      console.error(`Failed to download file. Status: ${xhr.status}`);
    }
  };

  xhr.onerror = function () {
    console.error("Request failed.");
  };

  xhr.send();
};
